package svgedit.gui.command;

import java.util.ArrayList;

import svgedit.gui.Frame;
import svgedit.svg.SVGElement;
import svgedit.svg.SVGGroup;

/**
 *  Define delete execution as a command object which has 
 *      execute (redo) and undo methods
 * */
public class DeleteCommand implements Command{

	private Frame frame;
	private ArrayList<SVGElement> elements = new ArrayList<SVGElement>();
	private ArrayList<SVGGroup> groups = new ArrayList<SVGGroup>();
	
	/** Constructor for delete command
	 * 
	 * @param frame get the singleton frame object 
	 * */
	public DeleteCommand(Frame frame){
		// Clear array list which contains the elements have been changed 
		elements.clear();
		groups.clear();
		this.frame=frame;
	}
	
	/** 
	 * To execute delete function or when user undo the deletion and redo it
	 * */
	public void execute(){
		// If the container is empty, execute to delete the selected items
		if(elements.size() == 0){
			for (SVGElement elem : frame.getView().getSelectedElements()){
			    elements.add(elem);
			    groups.add(elem.getParent());
	            elem.getParent().removeChild(elem);
		 }
		 
		}
		// Otherwise, redo to delete items in the container
		else{
			for (SVGElement elem : elements){
				elem.getParent().removeChild(elem);
			}
		}
	        frame.getDocument().setModified(true);
	        frame.getView().clearSelection();
	        frame.repaint();	
	}
	
	/**
	 *  Undo the execution , when delete some items, undo this execution to get these items back
	 * */
	public void undo(){
		for(int i =0; i < elements.size(); i++){
			groups.get(i).appendChild(elements.get(i));
		}
		frame.repaint();
	}
}
